package com.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.helper.DBHelper;
import com.model.Class;

public class ClassDao {

	private Class toClass(Map<String, Object> data) 
	{
		Class c = new Class();
		c.setId((Integer)data.get("id"));
		c.setName((String)data.get("name"));
		return c;
	}
	
	public Boolean add(String className) {
		String sql = "INSERT INTO `class` (`name`) VALUES ('"  + className + "');";
		DBHelper db = new DBHelper();
		return db.update(sql, null);
	}
	
	public Boolean delete(String className) {
		String sql = "DELETE FROM `class` WHERE `name`='"+className+"'";
		DBHelper db = new DBHelper();
		return db.update(sql, null);
	}

	public boolean rename(String name, String newname) {
		String sql = "UPDATE `class` SET `name`= '"+ newname +"' WHERE (`name`='"+ name +"')";
		DBHelper db = new DBHelper();
		return db.update(sql, null);
	}
	
	public Class getById(int id) {
		Class result = new Class();
		String sql = "select * from class where id=" + id;
		DBHelper db = new DBHelper();
		List<Map<String, Object>> data = db.query(sql, null);
		for(Map<String, Object> ele : data) {
			result = toClass(ele);
		}
		return result;
	}
	
	public Class getByName(String name) {
		Class result = new Class();
		String sql = "select * from class where name='" + name + "'";
		DBHelper db = new DBHelper();
		List<Map<String, Object>> data = db.query(sql, null);
		for(Map<String, Object> ele : data) {
			result = toClass(ele);
		}
		return result;
	}
	
	
	public List<Class> getAll() 
	{
		List<Class> result = new ArrayList<Class>();
		String sql = "select * from class";
		DBHelper db = new DBHelper();
		List<Map<String, Object>> data = db.query(sql, null);
		for(Map<String, Object> ele : data) {
			result.add(toClass(ele));
		}
		return result;
	}
}
